package com.itbac.service;

import com.itbac.loadbalance.LoadBalancer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * 订单服务
 * @author: BacHe
 * @email: 1218585258@qq.com
 * @Date: 2020/9/6 21:32
 */
@RestController
public class OrderService {

    @Autowired
    private DiscoveryClient discoveryClient;
    @Resource(name = "restTemplate")
    private RestTemplate restTemplate;
    @Resource(name = "restTemplateLoadBalanced")
    private RestTemplate restTemplateLoadBalanced;
    //手写的负载均衡
    @Autowired
    private LoadBalancer loadBalancer;
    //springcloud的负载均衡
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    /**
     * 通过手写的负载均衡
     * 注意：restTemplate()上不能加注解 @LoadBalanced
     */
    //订单服务中 去调 会员服务
    @RequestMapping("/orderToMember")
    public String orderToMember(){
        //1.根据服务名称，从注册中心获取服务地址列表

        List<ServiceInstance> serviceInstances = discoveryClient.getInstances("member");
        //通过手写的负载均衡算法，获取服务实例
        ServiceInstance serviceInstance = loadBalancer.getSingleAddress(serviceInstances);
        //2.调用会员服务
        String rsp = restTemplate.getForObject(serviceInstance.getUri()+"/getUser", String.class);
        return rsp;
    }
    /**
     * 通过Ribbon实现本地的负载均衡
     * 需要在 com.itbac.config.AppConfig#restTemplate()上加注解 @LoadBalanced
     */
    @RequestMapping("/orderToRibbonMember")
    public String orderToRibbonMember() {
        //1.通过 ribbon调用会员服务
        String rsp = restTemplateLoadBalanced.getForObject("http://member/getUser", String.class);
        return "ribbon调用会员服务:"+rsp;
    }

    /**
     * SpringCloud的本地负载均衡接口
     * 注意：restTemplate()上不能加注解 @LoadBalanced
     */
    @RequestMapping("/loadBalancerClientToMember")
    public String loadBalancerClientToMember() {
        //1.通过 SpringCloud的本地负载均衡接口，获取会员服务
        ServiceInstance serviceInstance = loadBalancerClient.choose("member");
        //2.调用会员服务
        String rsp = restTemplate.getForObject(serviceInstance.getUri()+"/getUser", String.class);
        return rsp;
    }

}
